package io.gitee.macxiang.config;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;

import com.alibaba.fastjson2.JSONObject;

import io.gitee.macxiang.entity.ApiResponse;
import io.gitee.macxiang.utils.utils;

import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class GlobalExceptionHandler {

  /**获取Exception错误信息的文本
  * @param e 报错内容
  * @return  错误文本
  */
  private String errString(Exception e) {
    String s = null;
    if (e != null) {
      s = e.getMessage();
      if (e instanceof InvocationTargetException) {
        s = ((InvocationTargetException) e).getTargetException().getMessage();
      }
      // StackTraceElement[] st = e.getStackTrace();
      // if (st.length > 0) {
      // s += " 文件定位: " + st[0].getFileName() + ":" + st[0].getLineNumber();
      // }
    }
    return s;
  }

  @ExceptionHandler(Exception.class)
  public ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
    Map<String, Object> body = new HashMap<>();
    String msg = errString(ex);
    body.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
    body.put("message", msg);

    // 设置自定义请求头
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
        .header("message", msg)
        .body(body);
  }

  @ExceptionHandler(RuntimeException.class)
  public ResponseEntity<Object> handleRuntimeExceptions(RuntimeException ex, WebRequest request) {
    String msg = utils.errString(ex);
    int code = HttpStatus.BAD_REQUEST.value();
    Object body = null;
    if (msg != null && msg.indexOf("{") == 0) {
      ApiResponse t = utils.parseJavaObject(msg, ApiResponse.class);
      if (t == null) {
        msg = new ApiResponse(msg, code).toString();
      } else {
        code = t.code;
        if (t.data != null) {
          body = t.data;
          t.data = null;
          msg = t.toString();
        }
      }
    } else {
      msg = new ApiResponse(msg, code).toString();
    }
    if (utils.containsNonAscii(msg)) {
      try {
        msg = URLEncoder.encode(msg, "UTF-8").replace("+", "%20");
      } catch (Exception e) {
        msg = JSONObject.of("message", utils.errString(e)).toJSONString();
      }
    }
    // 设置自定义请求头
    return ResponseEntity.status(code)
        .header("message", msg)
        .body(body);
  }

  // 你可以根据需要添加更多的异常处理方法
}